// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace InterpriseSuiteEcommerceControls.Validators
{
    public class InputLengthValidator : InputValidator
    {
        public static readonly int NoMinLengthFilter = 0;
        public static readonly int NoMaxLengthFilter = int.MaxValue;

        private TextBox _controlToValidate;
        private int _minLength = NoMinLengthFilter;
        private int _maxLength = NoMaxLengthFilter;

        public InputLengthValidator(TextBox controlToValidate, int maxLength, string errorMessage) : this(controlToValidate, int.MinValue, maxLength, errorMessage) { }

        public InputLengthValidator(TextBox controlToValidate, int minLength, int maxLength, string errorMessage)
            : this(controlToValidate, minLength, maxLength, errorMessage, null)
        {
        }

        public InputLengthValidator(TextBox controlToValidate, int minLength, int maxLength, string errorMessage, InputValidator next)
            : base(errorMessage, next)
        {
            _controlToValidate = controlToValidate;
            _minLength = minLength;
            _maxLength = maxLength;

            _controlToValidate.MaxLength = maxLength;
        }

        public override bool SupportsClientSideValidation
        {
            get { return true; }
        }

        protected override bool EvaluateIsValid()
        {
            bool evaluationIsValid = true;

            if (_minLength == NoMinLengthFilter)
            {
                evaluationIsValid = _controlToValidate.Text.Length <= _maxLength; ;
            }
            else
            {
                evaluationIsValid = _controlToValidate.Text.Length >= _minLength && _controlToValidate.Text.Length <= _maxLength;
            }

            return evaluationIsValid;
        }

        public override string RenderInitialization()
        {
            return string.Format(
                    "new ise.Validators.InputLengthValidator('{0}', {1}, {2}, '{3}', {4})",
                    _controlToValidate.ClientID,
                    (_minLength == NoMinLengthFilter) ? "null" : _minLength.ToString(),
                    _maxLength,
                    this.ErrorMessage,
                    RenderChainedValidatorInitialization()
                );
            
        }
    }
}
